package com.jing.yuntuku.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.jing.yuntuku.exception.BusinessException;
import com.jing.yuntuku.exception.ErrorCode;
import com.jing.yuntuku.model.dto.file.UploadPictureResult;
import com.jing.yuntuku.service.OssPictureUploadTemplate;
import com.jing.yuntuku.utils.AliOssUtil;
import com.jing.yuntuku.utils.ThrowUtils;
import lombok.Setter;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

@Setter
@Service
public class FileeeManager {

    // 为模板类手动注入AliOssUtil（因模板类是抽象类，无法直接通过Spring注入，需手动设置）
    @Resource
    private AliOssUtil aliOssUtil;

    // -------------------------- 上传接口（适配原有调用方式） --------------------------
    /**
     * 本地文件上传（原有方法，内部调用模板类）
     */
    public UploadPictureResult uploadFileAndGetInfo(MultipartFile file, String ossFolderPath) {
        // 创建本地文件上传器实例
        OssPictureUploadTemplate uploader = new MultipartFileOssUploader();
        // 注入AliOssUtil（因模板类用@Resource注入，此处需手动设置，避免空指针）
        uploader.setAliOssUtil(aliOssUtil);
        // 调用模板方法上传
        return uploader.uploadPicture(file, ossFolderPath);
    }

    /**
     * URL图片上传（原有方法，内部调用模板类）
     */
    public UploadPictureResult uploadPictureByUrl(String fileUrl, String ossFolderPath) {
        // 创建URL上传器实例
        OssPictureUploadTemplate uploader = new UrlOssUploader();
        // 注入AliOssUtil
        uploader.setAliOssUtil(aliOssUtil);
        // 调用模板方法上传
        return uploader.uploadPicture(fileUrl, ossFolderPath);
    }

    // -------------------------- 原有删除/解析方法（保持不变） --------------------------
    public boolean deleteSinglePicture(String objectKey) {
        ThrowUtils.throwIf(objectKey == null || objectKey.trim().isEmpty(),
                ErrorCode.PARAMS_ERROR, "图片路径不能为空");

        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(aliOssUtil.getEndpoint(),
                    aliOssUtil.getAccessKeyId(), aliOssUtil.getAccessKeySecret());

            if (!ossClient.doesObjectExist(aliOssUtil.getBucketName(), objectKey)) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            }

            ossClient.deleteObject(aliOssUtil.getBucketName(), objectKey);
            return true;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除图片失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public int deleteMultiplePictures(List<String> objectKeys) {
        ThrowUtils.throwIf(objectKeys == null || objectKeys.isEmpty(),
                ErrorCode.PARAMS_ERROR, "图片路径列表不能为空");

        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(aliOssUtil.getEndpoint(),
                    aliOssUtil.getAccessKeyId(), aliOssUtil.getAccessKeySecret());

            DeleteObjectsRequest deleteRequest = new DeleteObjectsRequest(aliOssUtil.getBucketName());
            deleteRequest.setKeys(objectKeys);

            DeleteObjectsResult result = ossClient.deleteObjects(deleteRequest);
            return result.getDeletedObjects().size();
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量删除图片失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public String getObjectKeyFromUrl(String url) {
        ThrowUtils.throwIf(url == null || url.trim().isEmpty(),
                ErrorCode.PARAMS_ERROR, "URL不能为空");

        try {
            URL ossUrl = new URL(url);
            String path = ossUrl.getPath();
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            int queryIndex = path.indexOf("?");
            if (queryIndex != -1) {
                path = path.substring(0, queryIndex);
            }
            return path;
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的图片URL: " + e.getMessage());
        }
    }

}